<script setup lang="ts" name="inspection-index">
import {
  getCurrentInstance,
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
  onBeforeUnmount,
  shallowRef,
} from "vue";

// 引入富文本
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IEditorConfig } from "@wangeditor/editor";

import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Edit } from "@element-plus/icons-vue";
import { setAutoCheckALert, setAutoCheckData } from "@/utils/autoCheck";
import {
  allCameraList,
  getAutoCheckList,
  setAutoCheck_,
  setAutoCheckStatus,
} from "@/api/server_inspection";
import type { UploadProps, UploadUserFile } from "element-plus";
import { addAutoCheckLog } from "@/api/server_artificial";

const store = useStore();
const router = useRouter();
const allCheckList = ref<any[]>([]);
const allCheckListMap = ref<any>({});
const cameraList = ref<any[]>([]);
const inspectionIndex = ref(0);
const checkInfoDialogVisible = ref(false);
const autoCheckInfo = ref<any>({});
const getAllAutoCheckList = async (init?: string) => {
  let res = await getAutoCheckList({});

  console.log("getAllAutoCheckList", res);

  if (res.result == "success") {
    let list = res.autoCheckList || [];
    let newList = list.map((item: any) => {
      return {
        ...item,
        camera_list: item.camera_list.split(","),
      };
    });
    allCheckList.value = newList;
    allCheckListMap.value = newList.reduce(
      (places: any, place: any, i: any) => {
        places[place.auto_check_id] = place;
        return places;
      },
      {}
    );
    if (!init) {
      setAutoCheckData(list, store.state.serviceTime);
    }

    // setAutoCheckData(res.autoCheckList)
  }
};
const getCheckListItem = (id: number) => {
  return allCheckListMap.value[id] || {};
};
const getcameraTag = (list: any) => {
  let cList = cameraList.value;
  let tag: any = [];
  if (!list) return "";
  list.forEach((v: any) => {
    let find = cList.find((vv) => vv.camera_id == v);
    if (find) tag.push(find.camera_name);
  });
  return tag.join(",");
};
const getCameraList = async () => {
  let res = await allCameraList({});
  if (res.result == "success") {
    cameraList.value = res.list;
    // setAutoCheckData(res.autoCheckList)
  }
};

const addInspection = async (index: number) => {
  let data = getCheckListItem(index);
  inspectionIndex.value = index;
  autoCheckInfo.value = data;
  checkInfoDialogVisible.value = true;
};
const setAutoCheck = async () => {
  let params: any = autoCheckInfo.value;
  params.id = inspectionIndex.value;
  let res = await setAutoCheck_({
    ...params,
  });
  if (res.result == "success") {
    checkInfoDialogVisible.value = false;
    getAllAutoCheckList();
    ElMessage({
      type: "success",
      message: "编辑成功!",
    });
  }
};
// 运行
const ress: any = ref({});
const cameraid = ref('');
const autoCheckId = ref({});
const setAutoCheckStatus_ = async (id: number, status: string) => {
  cameraid.value = getcameraTag(getCheckListItem(id).camera_list);
  autoCheckId.value = getCheckListItem(id).auto_check_id;

  let res: any = await setAutoCheckStatus({
    id: id,
    status: status,
  });
  ress.value = res.autoCheckInfo;
  console.log('ress.value',cameraid.value);
  

  getAllAutoCheckList();
  if (status == "open") {
    // 弹窗
    dialogTableVisible.value = true;
    // let autoCheckInfo = res.autoCheckInfo;
    // autoCheckInfo.camera_list = autoCheckInfo.camera_list.split(",");
    // setAutoCheckALert(autoCheckInfo);
  } else {
    ElMessage({
      type: "success",
      message: "停止成功!",
    });
  }
};
// 提交文字
const textarea2 = ref("");
const open2 = async () => {
  disabled.value = true;
  setTimeout( ()=> {
      disabled.value = false;
    }, 2000);
  let res: any = await addAutoCheckLog({
    autoCheckId: autoCheckId.value,
    cameraId: cameraid.value,
    content: textarea2.value,
    result: "success",
  });
  // let res = await addAutoCheckLog({

  // })

  if (res.result == "success") {
    ElMessage({
      message: "智能巡检日志提交成功",
      type: "success",
    });
    textarea2.value = "";
    
    
  } 
  // else {
  //   ElMessage({
  //     message: "请输入巡检任务",
  //     type: "warning",
  //   });
  // }
};
onMounted(() => {
  getAllAutoCheckList("init");
  getCameraList();
});
const phonedialogVisible = ref(false);

const submit = async () => {};

// 弹窗编辑
const dialogTableVisible = ref(false);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("<p>hello</p>");

// 模拟 ajax 异步获取内容
onMounted(() => {
  setTimeout(() => {
    valueHtml.value = "<p>编辑内容</p>";
  }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入内容..." };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

// 提交图片
// const fileList = ref<UploadUserFile[]>([
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   }
// ])

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 提交按钮
const disabled = ref(false);
</script>

<template>
  <div class="inspection-page">
    <div class="inspection-block" v-for="item in 6" :key="item">
      <app-box
        class="inspection"
        :title="getCheckListItem(item).name || `日常巡检${item}`"
      >
        <template #more>
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            circle
            @click="addInspection(item)"
          />
          <el-button
            plain
            size="small"
            type="success"
            @click="setAutoCheckStatus_(item, 'open')"
            >运行</el-button
          >
          <el-button
            plain
            size="small"
            type="danger"
            @click="setAutoCheckStatus_(item, 'stop')"
            >停止</el-button
          >
        </template>
        <div class="inspection-info">
          <div>
            巡检时间 :
            <span
              >{{ getCheckListItem(item).begin }}-{{
                getCheckListItem(item).end
              }}</span
            >
          </div>
          <div>
            播放时间 :<span>{{ getCheckListItem(item).times }}分钟</span>
          </div>
          <div>
            播放时间间隔 :<span
              >{{ getCheckListItem(item).interval_times }}分钟</span
            >
          </div>
          <div class="camera_list">
            添加摄像头:
            <el-tooltip
              effect="light"
              :content="getcameraTag(getCheckListItem(item).camera_list)"
            >
              <span>{{
                getcameraTag(getCheckListItem(item).camera_list)
              }}</span>
            </el-tooltip>
          </div>
        </div>
      </app-box>
    </div>
    <!-- <div class="inspection-block">
        <app-box class="inspection" title="新增">
        <template #more></template>
        <div @click="addInspection(-1)" style="text-align: center;">
          <svg-icon
            icon-class="add"
            color="#a0bedb"
            style="width: 80px; height: 200px"
          ></svg-icon>
        </div>
      </app-box>
      </div> -->

    <el-dialog
      :close-on-click-modal="false"
      :title="`编辑日常巡检`"
      v-model="checkInfoDialogVisible"
      width="672px"
    >
      <el-form
        :model="autoCheckInfo"
        size="small"
        label-width="120px"
        class="warning-form-inline"
      >
        <el-form-item label="巡检名称">
          <el-input v-model="autoCheckInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="巡检时间">
          <el-time-picker
            format="HH:mm"
            value-format="HH:mm"
            v-model="autoCheckInfo.begin"
            placeholder="开始时间"
          >
          </el-time-picker>
          <span style="margin-right: 50px">--</span>
          <el-time-picker
            format="HH:mm"
            value-format="HH:mm"
            v-model="autoCheckInfo.end"
            placeholder="结束时间"
          >
          </el-time-picker>
        </el-form-item>
        <el-form-item label="播放时间">
          <el-select
            filterable
            clearable
            v-model="autoCheckInfo.times"
            placeholder="请选择"
          >
            <el-option label="1分钟" value="1"></el-option>
            <el-option label="5分" value="5"></el-option>
            <el-option label="10分钟" value="10"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="播放时间间隔">
          <el-select
            filterable
            clearable
            v-model="autoCheckInfo.interval_times"
            placeholder="请选择"
          >
            <el-option label="1分钟" value="1"></el-option>
            <el-option label="2分" value="2"></el-option>
            <el-option label="3分" value="3"></el-option>
            <el-option label="3分" value="4"></el-option>
            <el-option label="5分" value="5"></el-option>
            <el-option label="10分钟" value="10"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="添加摄像头">
          <el-select
            filterable
            clearable
            multiple
            style="width: 80%"
            v-model="autoCheckInfo.camera_list"
            placeholder="请选择"
          >
            <el-option
              :label="c.camera_name"
              :value="c.camera_id"
              :key="index"
              v-for="(c, index) in cameraList"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="text-align: right">
          <el-button type="primary" @click="setAutoCheck">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 弹窗编辑 -->
    <el-dialog
      v-model="dialogTableVisible"
      title="智能巡检"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="dialog-we-box">
        <div class="dialog-we-box-l">
          <div class="dialog-we-box-l-x">
            <span class="dialog-we-box-l-x-a">摄像头：</span>
            <span class="dialog-we-box-l-x-b">{{ cameraid }}</span>
            <span class="dialog-we-box-l-x-c">时间：</span>
            <span class="dialog-we-box-l-x-d">{{ ress.gmt_modified }}</span>
          </div>
          <video width="540"  controls>
            <!-- <source :src="item.url" type="video/mp4" /> -->
            <source src="../../../assets/image/video.mp4" type="video/mp4" />
          </video>
        </div>
        <div class="dialog-we-box-r">
          <div class="dialog-we-box-text">
            <div class="dialog-we-box-text-a">
              <div class="dialog-we-box-l-x">
                <span class="dialog-we-box-l-x-b">{{ ress.name }}</span>
              </div>
              <el-input
                class="inputcol"
                v-model="textarea2"
                :autosize="{ minRows: 14, maxRows: 14 }"
                type="textarea"
                placeholder="编写内容......"
              />
            </div>
            <div class="dialog-we-box-text-b"></div>
          </div>
          <!-- <div class="dialog-we-box-text-btn" ></div> -->
          <el-button :disabled="disabled" type="success" plain @click="open2"
            >提交内容</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
// 弹窗样式
.dialog-we-box {
  display: flex;
  justify-content: space-around;

  .dialog-we-box-l {
    width: 550px;

    .dialog-we-box-l-x {
      .dialog-we-box-l-x-a {
        color: #c0c0c0;
        font-size: 18px;
        line-height: 50px;
      }
      .dialog-we-box-l-x-b {
        color: #2bc994;
        font-size: 18px;
        line-height: 50px;
      }
      .dialog-we-box-l-x-c {
        color: #c0c0c0;
        font-size: 18px;
        line-height: 50px;
        margin-left: 25px;
      }
      .dialog-we-box-l-x-d {
        color: #2bc994;
        font-size: 18px;
        line-height: 50px;
      }
    }
  }
  .dialog-we-box-r {
    .dialog-we-box-l-x {
      .dialog-we-box-l-x-a {
        color: #2bc994;
        font-size: 18px;
        line-height: 50px;
      }
      .dialog-we-box-l-x-b {
        color: #d9e445;
        font-size: 18px;
        line-height: 50px;
      }
    }
    .dialog-we-box-text {
      display: flex;
      justify-content: space-between;

      .dialog-we-box-text-a {
        width: 300px;
        height: 380px;
      }
      // .dialog-we-box-text-b {
      //   margin-left: 10px;
      //   width: 360px;
      //   height: 400px;
      //   overflow: auto;
      // }
    }
    .dialog-we-box-text-btn {
      background-color: #1c8160;
      width: 300px;
      height: 35px;
      border-radius: 20px;
      margin-top: 15px;
      margin: 15px auto 0 auto;
      font-size: 18px;
      text-align: center;
      line-height: 35px;
      cursor: pointer;
    }
    .dialog-we-box-text-btn:hover {
      background-color: #209292;
      user-select: none;
    }
  }
}
.inspection-page {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;

  .inspection-block {
    width: 33%;
    height: 50%;
    padding: 10px;
  }

  .inspection {
    height: 100%;
    width: 100%;
    margin: 10px;
    cursor: pointer;

    .inspection-info {
      .camera_list {
        height: 50px;
        line-height: 25px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        padding: 0 0;
      }

      & > div {
        padding: 10px 0;
        text-align: left;

        span {
          color: #a0bedb;
          font-weight: bold;
        }
      }
    }
  }
}

.content {
  display: flex;
}

.content-left {
  width: 75%;
}

.content-right {
  margin-left: 30px;
}
.content-right text {
  margin-bottom: 15px;
}
.inputcol {
  background-color: #0e0e0e;
}
</style>
